package com.tjnu.baiyi.dao;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.tjnu.baiyi.entity.TbAlbum;
import com.tjnu.baiyi.entity.TbAlbumVisitor;

@Repository("tbAlbumDao")
@Transactional
public class TbAlbumDAO {
	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	protected void initDao() {
		// do nothing
	}

	// 创建新的相册
	public Boolean createAlbum(String albumName, Integer typeId,
			String albumRestrict, Integer userId) {
		try {
			System.out.println("TbAlbumDAO.createAlbum()");
			String queryString1 = new StringBuffer()
					.append("INSERT INTO tb_album (Album_name,Album_type_Id,Album_restrict,User_id,Album_hot) VALUES(?,?,?,?,?)")
					.toString();
			Query queryObject1 = getCurrentSession()
					.createSQLQuery(queryString1).addEntity(TbAlbum.class)
					.setString(0, albumName).setInteger(1, typeId)
					.setString(2, albumRestrict).setInteger(3, userId)
					.setInteger(4, 0);
			int i = queryObject1.executeUpdate();
			System.out.println("queryObject1.executeUpdate():" + i);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	// 验证表中是否有符合条件的记录
	public Boolean validateUserAndAlbum(Integer userId, Integer albumId) {
		try {
			String queryString = new StringBuffer().append(
					"FROM TbAlbum WHERE tbUser.userId = ? AND albumId = ?")
					.toString();
			Query queryObject = getCurrentSession().createQuery(queryString)
					.setInteger(0, userId).setInteger(1, albumId);
			List<TbAlbum> list = queryObject.list();
			if (list.size() != 1) {// 不存在符合条件的记录，或存在多条符合条件的记录
				return false;
			} else {// 存在符合条件的记录为1条
				return true;
			}
		} catch (Exception e) {
			return false;
		}
	}

	public void save(TbAlbum transientInstance) {
		try {
			getCurrentSession().save(transientInstance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void delete(TbAlbum persistentInstance) {
		try {
			getCurrentSession().delete(persistentInstance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public TbAlbum findById(java.lang.Integer id) {
		try {
			TbAlbum instance = (TbAlbum) getCurrentSession().get(TbAlbum.class,
					id);
			return instance;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public Integer getfindAllSize() {
		try {
			String queryString = new StringBuffer().append(
					"SELECT count(*) FROM TbAlbum ORDER BY albumHot DESC")
					.toString();
			Query queryObject = getCurrentSession().createQuery(queryString);
			int totalRecords = ((Long) queryObject.uniqueResult()).intValue();// 类型转换
			return totalRecords;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List<TbAlbum> findAllByPage(Integer page) {
		try {
			String queryString = new StringBuffer().append(
					"FROM TbAlbum ORDER BY albumHot DESC").toString();
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setFirstResult(page * 20);
			queryObject.setMaxResults(20);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List<TbAlbum> findAllMyAlbumBytbAlbumTypeId(Integer id) {
		try {
			String queryString = new StringBuffer()
					.append("FROM TbAlbum WHERE tbUser.userId=? ORDER BY tbAlbumType.albumTypeId ASC")
					.toString();
			Query queryObject = getCurrentSession().createQuery(queryString)
					.setInteger(0, id);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	// 对某个相册点赞（更新点赞数）
	public Boolean updateAlbumHot(Integer id, Integer albumHot) {
		try {
			String queryString = new StringBuffer().append(
					"UPDATE TbAlbum SET albumHot =? WHERE albumId=?")
					.toString();
			Query queryObject = getCurrentSession().createQuery(queryString)
					.setInteger(0, albumHot + 1).setInteger(1, id);
			queryObject.executeUpdate();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	// 添加访问相册的访客记录
	public void updateTbAlbumVisitor(Integer albumId, Integer userId,
			Integer visitorSize) {
		try {
			// 验证相册所属的用户id是否已经登录
			String queryString = new StringBuffer().append(
					"FROM TbAlbum WHERE albumId=? AND tbUser.userId=?")
					.toString();
			Query queryObject = getCurrentSession().createQuery(queryString)
					.setInteger(0, albumId).setInteger(1, userId);
			List<TbAlbum> list = queryObject.list();
			if (list.size() == 0) {// 该相册不是已经登录了的用户的相册，需要添加访客记录
				// 判断是否有相应的记录
				String validateString = new StringBuffer()
						.append("FROM TbAlbumVisitor WHERE tbAlbum.albumId=? AND tbUser.userId=?")
						.toString();
				Query queryValidateObject = getCurrentSession()
						.createQuery(validateString).setInteger(0, albumId)
						.setInteger(1, userId);
				List<TbAlbum> validateList = queryValidateObject.list();
				if (validateList.size() != 0) {// 有相应的记录，对记录中的时间字段进行更新
					System.out.println("validateList.size() != 0");
					String queryString1 = new StringBuffer()
							.append("UPDATE tb_album_visitor SET Album_visitor_time = ? WHERE Album_id=? AND Album_visitor_id=?")
							.toString();
					System.out.println("validateList.size() != 0 and query");
					Query queryObject1 = getCurrentSession()
							.createSQLQuery(queryString1)
							.addEntity(TbAlbumVisitor.class)
							.setTimestamp(0, getCurrentTime())
							.setInteger(1, albumId).setInteger(2, userId);
					int i = queryObject1.executeUpdate();
					System.out.println("queryObject1.executeUpdate():" + i);
				} else {// 没有相应的记录，向访问表中添加纪录
					String queryString2 = new StringBuffer()
							.append("INSERT INTO tb_album_visitor (Album_visitor_id,Album_visitor_time,Album_id) VALUES(?,?,?)")
							.toString();
					Query queryObject2 = getCurrentSession()
							.createSQLQuery(queryString2)
							.addEntity(TbAlbumVisitor.class)
							.setInteger(0, userId)
							.setTimestamp(1, getCurrentTime())
							.setInteger(2, albumId);
					int i = queryObject2.executeUpdate();
					System.out.println("queryObject1.executeUpdate():" + i);
				}
				// 更新该相册的访问总数
				String queryString2 = new StringBuffer().append(
						"UPDATE tb_album SET visitor_size =? WHERE album_id=?")
						.toString();
				Query queryObject2 = getCurrentSession()
						.createSQLQuery(queryString2).addEntity(TbAlbum.class)
						.setInteger(0, visitorSize + 1).setInteger(1, albumId);
				int j = queryObject2.executeUpdate();
			} else {// 该相册是已经登录了的用户的相册，不添加访客记录
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 获取当前时间
	public Timestamp getCurrentTime() {
		// 使用默认时区和语言环境获得一个日历
		Calendar calender = Calendar.getInstance();
		// 将Calendar类型转换成Date类型
		Date tasktime = (Date) calender.getTime();
		// 设置日期输出的格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Timestamp time = Timestamp.valueOf(df.format(tasktime));
		return time;
	}
}